# @Time    : 2017/12/12 下午1:21
# @Author  : JCD
# @File    : tools.py
from http.cookiejar import CookieJar, Cookie
import time


def dict2cookiejar(cookie_dict):
    cookie_jar = CookieJar()
    for cookie in cookie_dict:
        cookie_temp = Cookie(version=0, name=cookie['name'], value=cookie['value'],
                             port=None, port_specified=False,
                             domain=cookie['domain'], domain_specified=False, domain_initial_dot=False,
                             path='', path_specified=False,
                             secure=False,
                             expires=int(time.time()) + 9999,
                             discard=False,
                             comment=None,
                             comment_url=None,
                             rest={},
                             rfc2109=False)
        cookie_jar.set_cookie(cookie_temp)
    return cookie_jar


def cookiejar2dict(cookiejar):
    result = []
    for cookie in cookiejar:
        domain = ''
        path = '/'
        expires = int(time.time()) + 9999
        if not (cookie.domain is None):
            domain = cookie.domain
            if -1 == domain.find('.', 0, 1):
                domain = '.' + domain
        if not(cookie.path is None) and not(cookie.path is ''):
            path = cookie.path
        if not (cookie.expires is None):
            expires = cookie.expires
        result.append({'name': cookie.name, 'value': cookie.value, 'domain': domain, 'path': path, 'expiry': expires})
    return result
